package com.ruoyi.project.service.impl;

import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.experiment.domain.Circulation;
import com.ruoyi.experiment.domain.Experiment;
import com.ruoyi.experiment.domain.Sample;
import com.ruoyi.experiment.mapper.ExperimentMapper;
import com.ruoyi.experiment.utils.Num;
import com.ruoyi.finance.model.Price;
import com.ruoyi.project.mapper.HandleMapper;
import com.ruoyi.project.model.BriefProject;
import com.ruoyi.project.model.ExperimentDetails;
import com.ruoyi.project.model.PExperiment;
import com.ruoyi.project.service.IHandleService;
import com.ruoyi.sample.mapper.SampleLzMapper;
import com.ruoyi.sample.mapper.SampleMapper;
import com.ruoyi.sample.model.SampleLz;
import com.ruoyi.summarize.mapper.SummarizeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HandleServiceImpl implements IHandleService {
    @Autowired
    HandleMapper handleMapper;
    @Autowired
    SampleMapper sampleMapper;
    @Autowired
    SampleLzMapper sampleLzMapper;
    @Autowired
    SummarizeMapper summarizeMapper;
    @Autowired
    ExperimentMapper experimentMapper;

    @Override
    public List<BriefProject> listBriefProject(BriefProject project) {
        project.setProjectLeaderId(SecurityUtils.getUserId());
        int i = handleMapper.hasAdmin(SecurityUtils.getUserId());
        if (i>0)
            project.setProjectLeaderId(1L);
        PageUtils.startPage();
        return handleMapper.selectBriefProject(project);
    }

    @Override
    public List<Experiment> listExperimentDetails(ExperimentDetails experimentDetails) {
        Long projectId = experimentDetails.getProjectId();
        List<Long> ids = handleMapper.selectRootSampleByProjectId(projectId);
        List<Experiment> res= new ArrayList<>();
        for (Long id : ids) {
            List<Long> t=new ArrayList<>();
            t.add(id);
            selectTree(id,t);
            List<Experiment> experiments = handleMapper.selectExperimentsBySampleIds(t);
            for (Experiment experiment : experiments) {
                experiment.setSampleId(id);
            }
            res.addAll(experiments);
        }
        return res;
    }

    public void selectTree(Long id,List<Long> res){
        List<Long> longs = handleMapper.selectSampleIdByParentId(id);
        if (longs==null)
            return;
        res.addAll(longs);
        for (Long cid : longs) {
            selectTree(cid,res);
        }
    }

    @Override
    public List<PExperiment> listPostByProjectId(PExperiment post) {
        List<PExperiment> pExperiments = handleMapper.selectPostByProjectId(post);
        for (PExperiment pExperiment : pExperiments) {
            Sample sample = selectRootSample(pExperiment.getSampleId());
            pExperiment.setSampleName(sample.getSampleName());
        }
        return pExperiments;
    }
    @Override
    public List<PExperiment> listPostByProjectId2(PExperiment post) {
        List<PExperiment> pExperiments = handleMapper.selectPostByProjectId2(post);
        for (PExperiment pExperiment : pExperiments) {
            Sample sample = selectRootSample(pExperiment.getSampleId());
            pExperiment.setSampleName(sample.getSampleName());
        }
        return pExperiments;
    }

    @Override
    public List<PExperiment> listExperimentByProjectId(PExperiment post) {
        List<PExperiment> pExperiments = handleMapper.selectExperimentByProjectId(post);
        for (PExperiment pExperiment : pExperiments) {
            Sample sample = selectRootSample(pExperiment.getSampleId());
            pExperiment.setSampleName(sample.getSampleName());
        }
        return pExperiments;
    }
    @Override
    public List<PExperiment> listExperimentByProjectId2(PExperiment post) {
        List<PExperiment> pExperiments = handleMapper.selectExperimentByProjectId2(post);
        for (PExperiment pExperiment : pExperiments) {
            Sample sample = selectRootSample(pExperiment.getSampleId());
            pExperiment.setSampleName(sample.getSampleName());
        }
        return pExperiments;
    }
    private Sample selectRootSample(Long id){
        Sample sample = sampleMapper.selectParentSample(id);
        if (sample.getParentId()==-1)
            return sample;
        return selectRootSample(sample.getParentId());
    }

    @Override
    public void confirmPost(Long id) {
        Integer type = handleMapper.getTypeById(id);
        int i = Num.get(type, 2);
        if (i==3){
            handleMapper.updateType(id,Num.set(type,2,4));
            Circulation circulation = new Circulation();
            circulation.setProjectId(handleMapper.selectPidByEid(id));
            circulation.setCirculationType(10);
            circulation.setUserName(SecurityUtils.getUsername());
            circulation.setCirculationSuggestion("流转岗位信息至财务");
            handleMapper.insertFlume(circulation);
        }
    }

    @Override
    public void backPost(Long id) {
        Integer type = handleMapper.getTypeById(id);
        int i = Num.get(type, 2);
        if (i==3){
            handleMapper.updateType(id,Num.set(type,2,2));
        }
    }

    @Override
    @Transactional
    public void confirmExperiment(Long id) {
        Integer type = handleMapper.getTypeById(id);
        int i = Num.get(type, 3);
        if (i==1){
            handleMapper.updateType(id,Num.set(type,3,2));
            Circulation circulation = new Circulation();
            circulation.setProjectId(handleMapper.selectPidByEid(id));
            circulation.setCirculationType(10);
            circulation.setUserName(SecurityUtils.getUsername());
            circulation.setCirculationSuggestion("流转实验信息至财务");
            handleMapper.insertFlume(circulation);
        }
    }

    @Override
    public void backExperiment(Long id) {
        Integer type = handleMapper.getTypeById(id);
        int i = Num.get(type, 3);
        if (i==1){
            handleMapper.updateType(id,type%100);
        }
    }

    @Override
    public String finish(Long id) {
        Integer count = handleMapper.countExperiment(id);
        Integer finish = summarizeMapper.selectFinishByPid(id);
        Price price1 = handleMapper.selectSumPrice(id);
        Price price2 = handleMapper.selectProjectPrice(id);
        //检测样品是否流转回样品管理员
        Integer c2 = handleMapper.countUnFinishSample(id);
        if (c2>0)
            return "存在未流转回样品管理员的样品";
        if (price1==null)
            price1=new Price();
        if (price2==null)
            price2=new Price();
        price2.setP1(price2.getP1());
        if (price2.getP1()+1<price1.getP1()){
            return "支付计划未设置完";
        }
        if (count!=0 )
            return "存在实验未完成";
        if (finish==null || finish==0)
            return "未归档";
        handleMapper.finishProject(id);
        return null;
    }

    @Override
    public void flume(Circulation circulation) {
        circulation.setUserName(SecurityUtils.getUsername());
        switch (circulation.getCirculationType()) {
            case 6:
                for (Long id : circulation.getIds()) {
                    confirmLZ(1,id);
                }
                sampleMapper.insertFlume(circulation);
                backToSample(circulation.getProjectId(), circulation.getIds());
                break;
            case 5:
                apllyForSample(circulation.getProjectId(), circulation.getIds());
                break;
        }
    }
    private boolean confirmLZ(Integer status, Long id) {
        Sample sample = new Sample();
        sample.setSampleId(id);
        sample.setConfirmStatus(status);
        int i = sampleMapper.updateSample(sample);
        return i==1;
    }

    @Override
    public void updateExperiment(Experiment experiment) {
        experimentMapper.updateExperimentalManagement(experiment);
    }

    private void backToSample(Long pid, List<Long> ids){
        Sample sample = new Sample();
        sample.setProjectId(pid);
        List<Sample> samples = sampleMapper.selectSampleList(sample);
        Map<Long, Sample> map = new HashMap<>();
        for (Sample s : samples) {
            map.put(s.getSampleId(), s);
        }
        for (Long id : ids) {
            Sample s = map.get(id);
            if (s.getSampleStatus() ==4) {
                s.setSampleStatus(0);
                sampleMapper.updateSample(s);
                sampleLzMapper.insertSampleLz(new SampleLz(s.getSampleId(),"归还至样品管理员",s.getSampleQuantity(),s.getSampleSize()));
            }
        }
    }
    private void apllyForSample(Long pid, List<Long> ids){
        for (Long id : ids) {
            Sample sample = sampleMapper.selectSampleBySampleId(id);
            Circulation circulation = new Circulation();
            circulation.setSampleId(sample.getSampleId());
            circulation.setCirculationType(6);
            circulation.setProjectId(sample.getProjectId());
            circulation.setCirculationSuggestion("请求将样品"+ sample.getSampleName()+"流转至项目管理员");
            circulation.setUserName(SecurityUtils.getUsername());
            sampleMapper.insertFlume(circulation);
        }
    }

}
